<template>
  <el-config-provider :locale="zhCn">
    <div class="page">
      <div class="toolbar">
        <el-form :inline="true" class="filters">
          <el-form-item label="编号"><el-input v-model="header.code" disabled style="width:200px" /></el-form-item>
          <el-form-item label="名称"><el-input v-model="header.name" disabled style="width:240px" /></el-form-item>
          <el-form-item>
            <el-button type="primary" @click="openCreate">新建版本</el-button>
            <el-button @click="cloneLatest">基于最新生成</el-button>
          </el-form-item>
        </el-form>
        <div class="actions">
          <el-form :inline="true">
            <el-form-item>
              <el-button @click="goBack">返回</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="table-area">
        <div class="table-container">
          <el-table :data="rows" style="width:100%" max-height="100%">
            <el-table-column prop="version_no" label="版本号" width="100" />
            <el-table-column label="评估模板" min-width="260">
              <template #default="{ row }">{{ row.template_version_code }} {{ templateNameOf(row.template_version_code) }}</template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120" />
            <el-table-column prop="adopted" label="是否采用" width="120">
              <template #default="{ row }">{{ row.adopted ? '是' : '否' }}</template>
            </el-table-column>
            <el-table-column label="下载链接" min-width="260">
              <template #default="{ row }">
                <template v-if="row.download_rel_path_docx">
                  <a :href="downloadHref(row.download_rel_path_docx)" target="_blank">DOCX</a>
                </template>
                <template v-if="row.download_rel_path_pdf">
                  <span style="margin:0 8px">｜</span>
                  <a :href="downloadHref(row.download_rel_path_pdf)" target="_blank">PDF</a>
                </template>
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="创建时间" min-width="180" />
            <el-table-column prop="updated_at" label="更新时间" min-width="180" />
            <el-table-column label="操作" width="380" fixed="right">
              <template #default="{ row }">
                <el-button @click="edit(row)">编辑</el-button>
                <el-button @click="finalize(row)" :disabled="row.status==='final'">定版</el-button>
                <el-button @click="adopt(row)" :disabled="row.status!=='final' || row.adopted">采用</el-button>
                <el-button type="danger" @click="remove(row)" :disabled="row.adopted">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
          <el-config-provider :locale="zhCn">
            <el-pagination
              background
              layout="prev, pager, next, sizes, jumper, total"
              :total="total"
              :page-size="pageSize"
              :current-page="page"
              :page-sizes="[10,20,50,100]"
              @size-change="onSizeChange"
              @current-change="onPageChange"
            />
          </el-config-provider>
        </div>
      </div>
      <el-dialog v-model="showCreate" title="新建版本">
        <el-form label-width="100px">
          <el-form-item label="编号"><el-input v-model="header.code" disabled /></el-form-item>
          <el-form-item label="名称"><el-input v-model="header.name" disabled /></el-form-item>
          <el-form-item label="评估模板">
            <el-select v-model="newVersion.template_version_code" placeholder="选择评估模板" style="width:100%">
              <el-option v-for="t in templates" :key="t.template_version_code" :label="t.name+'('+t.template_version_code+')'" :value="t.template_version_code" />
            </el-select>
          </el-form-item>
          <el-form-item label="版本标题"><el-input v-model="newVersion.title" /></el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showCreate=false">取消</el-button>
          <el-button type="primary" @click="createVersion" :disabled="!newVersion.template_version_code || !newVersion.title">创建</el-button>
        </template>
      </el-dialog>
    </div>
  </el-config-provider>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { useRoute, useRouter } from 'vue-router'
import { api } from '../../api/client'

const route = useRoute()
const router = useRouter()
const headerId = route.params.headerId as string
const header = ref<any>({ code:'', name:'' })
const rows = ref<any[]>([])
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const templates = ref<any[]>([])
const newVersion = ref<any>({ template_version_code:'', title:'' })
const showCreate = ref(false)

async function load(){
  const h = await api.get(`/report-headers/`)
  const hdata = h.data
  const headers = Array.isArray(hdata?.items) ? hdata.items : Array.isArray(hdata) ? hdata : []
  header.value = headers.find(x => x.id === headerId) || { code:'', name:'' }
  const res = await api.get(`/report-versions/by-header/${headerId}`, { params: { page: page.value, page_size: pageSize.value } })
  const data = res.data
  rows.value = Array.isArray(data.items) ? data.items : Array.isArray(data) ? data : []
  total.value = typeof data.total === 'number' ? data.total : rows.value.length
}

async function loadTemplates(){
  const { data } = await api.get('/evaluation-templates')
  templates.value = data
}

function openCreate(){
  newVersion.value = { template_version_code:'', title:'' }
  showCreate.value = true
}
async function createVersion(){
  if(!newVersion.value.template_version_code || !newVersion.value.title){
    ElMessage.error('请选择评估模板并填写版本标题')
    return
  }
  try{
    const { data } = await api.post(`/report-versions/by-header/${headerId}`, {
      report_id: headerId,
      template_version_code: newVersion.value.template_version_code,
      title: newVersion.value.title,
    })
    newVersion.value = { template_version_code:'', title:'' }
    await load()
    showCreate.value = false
    ElMessage.success('已新建版本')
  }catch(e:any){
    ElMessage.error(e?.response?.data?.detail || '新建版本失败')
  }
}

async function cloneLatest(){
  try{
    await api.post(`/report-versions/by-header/${headerId}/clone-latest`)
    await load()
    ElMessage.success('已基于最新生成新版本')
  }catch(e:any){
    ElMessage.error(e?.response?.data?.detail || '生成失败')
  }
}

  function edit(row:any){
    router.push(`/admin/report-versions/${row.id}/editor`)
  }

async function finalize(row:any){
  await api.post(`/report-versions/${row.id}/finalize`)
  await load()
}

async function adopt(row:any){
  await api.post(`/report-versions/${row.id}/adopt`)
  await load()
}

  async function remove(row:any){
    await api.delete(`/report-versions/${row.id}`)
    await load()
  }

onMounted(async()=>{ await load(); await loadTemplates() })

function onPageChange(p: number){
  page.value = p
  load()
}

  function onSizeChange(s: number){
    pageSize.value = s
    page.value = 1
    load()
  }

  function goBack(){
    router.push('/admin/report-headers')
  }

  function templateNameOf(code: string){
    const list = Array.isArray(templates.value?.items) ? templates.value.items : Array.isArray(templates.value) ? templates.value : []
    const t = list.find((x: any) => x.template_version_code === code)
    return t?.name || ''
  }

function downloadHref(rel: string){
  const r = String(rel || '')
  if(!r) return '#'
  const origin = window.location.origin
  return origin + r
}
</script>

<style scoped>
.page { 
  height: 100%; 
  display: flex; 
  flex-direction: column; 
  box-sizing: border-box;
  overflow: hidden;
}
.toolbar { 
  flex-shrink: 0; 
  display: flex; 
  align-items: center; 
  justify-content: space-between; 
  gap: 12px; 
  padding-bottom: 16px; 
  box-sizing: border-box;
}
.filters { flex: 1; }
.actions { flex-shrink: 0; }
.table-area { 
  flex: 1; 
  display: flex; 
  flex-direction: column; 
  min-height: 0;
  overflow: hidden;
}
.table-container {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-height: 0;
  position: relative;
}
.table-container :deep(.el-table) {
  height: 100% !important;
  display: flex;
  flex-direction: column;
  flex: 1;
}
.table-container :deep(.el-table__inner-wrapper) {
  height: 100% !important;
  display: flex;
  flex-direction: column;
  flex: 1;
}
.table-container :deep(.el-table__header-wrapper) {
  flex-shrink: 0;
  height: auto !important;
}
.table-container :deep(.el-table__body-wrapper) {
  flex: 1;
  overflow-y: auto !important;
  height: auto !important;
  min-height: 200px;
}
.table-container :deep(.el-table__empty-block) {
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.pagination { 
  flex-shrink: 0; 
  display: flex; 
  justify-content: flex-end; 
  padding-top: 16px; 
  padding-bottom: 8px;
  box-sizing: border-box;
  background: white;
  border-top: 1px solid #f0f0f0;
  margin-top: auto;
}
@media (max-width: 768px) {
  .toolbar { flex-direction: column; align-items: stretch; }
  .filters { margin-bottom: 12px; }
  .pagination { justify-content: center; }
}
</style>
